package leecode

import "math"

func findClosest(words []string, word1 string, word2 string) int {
	hashMap := make(map[string][]int) //key为单词 , value为单词出现的下标
	for i := 0; i < len(words); i++ {
		hashMap[words[i]] = append(hashMap[words[i]], i)
	}
	word1Index := hashMap[word1]
	word2Index := hashMap[word2] //两个有序切片
	i, j := 0, 0
	result := math.MaxInt
	for i < len(word1Index) && j < len(word2Index) {
		result = min(absM(word1Index[i]-word2Index[j]), result)
		if word1Index[i] > word2Index[j] {
			j++
		} else if word2Index[j] > word1Index[i] {
			i++
		}
	}
	return result
}

func absM(a int) int {
	if a < 0 {
		return -a
	}
	return a
}
